<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Group extends Admin_Controller
{
	public function __construct()
	{
		parent::__construct();

		$this->load->model('user_model');
		$this->load->model('role_model');
		$this->load->model('user_temp_model');
		$this->load->model('permission_model');
		$this->load->model('user_profile_model');

		$this->template->set_breadcrumb('Nhóm người dùng', 'backend/group');
	}

	public function index()
	{
		//$this->auth->check_uri_permissions(true, 'backend/login');
		$this->template->title('SeoShop', 'Nhóm người dùng');
		$this->template->build('backend/group/group', $this->data);
	}

	public function load($order_by = 'id', $order_dir = 'asc', $page = 1)
	{
		$pager_config['base_url'] = base_path() . "backend/group/load/{$order_by}/{$order_dir}/";
		$pager_config['uri_segment'] = 6;
		$pager_config['num_links'] = 3;
		$pager_config['total_rows'] = $this->role_model->count(array('status' => 1));
		$pager_config['per_page'] = 20;

		$limit = $pager_config['per_page'];
		$offset = $page ? (($page - 1) * $limit) : 0;
		$roles = $this->role_model->find(array('status' => 1), "{$order_by} {$order_dir}", $limit, $offset)->result();
		$data['sql'] = $this->db->last_query();

		$data['rows'] = "";
		foreach ($roles as $row)
		{
			$data['rows'].= "<tr><td><input type=\"checkbox\" name=\"items[]\" value=\"{$row->id}\" /></td>";
			$data['rows'].= "<td>" . $row->name . "</td>";
			$data['rows'].= "<td>" . $row->description . "</td>";
			$data['rows'].= "<td align=\"center\"><div><a href=\"". base_path() . "backend/group/update/{$row->id}\" class=\"edit\">Edit</a></div></td></tr>";
		}

		$data['from_record'] 	= $pager_config['total_rows'] == 0 ? 0 : $offset + 1;
		$data['to_record'] 	= $offset + $limit > $pager_config['total_rows'] ? $pager_config['total_rows'] : $offset + $limit;
		$data['total_record'] = $pager_config['total_rows'];

		$this->pagination->initialize($pager_config);
		$data['pagination'] = $this->pagination->create_links();
		$data['message'] = 'OK';

		echo json_encode($data);
	}

	public function create()
	{
		$this->data['message'] = '';
		$validator = $this->form_validation;
		$validator->set_rules('name', 'Tên nhóm', 'trim|required|xss_clean|min_length[3]|max_length[32]|callback_check_role|alpha_dash');
		$validator->set_rules('description', 'Mô tả', 'trim|xss_clean');
		$validator->set_rules('uris', 'Phân quyền dựa trên URI', 'trim');
		if($validator->run())
		{
			$created = date('Y-m-d H:i:s');

			$data['name'] = $validator->set_value('name');
			$data['description'] = $validator->set_value('description');
			$data['created'] = $created;

			$role_id = $this->role_model->save($data);

			$allowed_uris = array();
			$uris = explode("\r\n", $validator->set_value('uris'));
			foreach ($uris as $uri)
			{
				$allowed_uris[] = trim($uri);
			}

			if($role_id && $this->permission_model->set_permission_value($role_id, 'uri', $allowed_uris))
			{
				$this->data['message'] = 'Dữ liệu thêm vào thành công';
			}
			else
			{
				$this->data['message'] = 'Có lỗi xảy ra';
			}
		}
		else
		{
			$this->data['message'] = validation_errors('<span>', '</span>');
		}

		$this->template->set_breadcrumb('Tạo mới', 'backend/group/create');
		$this->template->title('SeoShop', 'Nhóm người dùng', 'Tạo mới');
		$this->template->build('backend/group/create', $this->data);
	}

	public function update($role_id = NULL)
	{
		if($role_id)
		{
			$this->data['message'] = '';

			$validator = $this->form_validation;
			$validator = $this->form_validation;
			$validator->set_rules('name', 'Tên nhóm', 'trim|required|xss_clean|min_length[3]|max_length[32]|callback_check_role|alpha_dash');
			$validator->set_rules('description', 'Mô tả', 'trim|xss_clean');
			$validator->set_rules('uris', 'Phân quyền dựa trên URI', '');

			if($validator->run())
			{
				$data['name'] = $validator->set_value('name');
				$data['description'] = $validator->set_value('description');

				$this->role_model->update(array('id' => $role_id), $data);

				$allowed_uris = array();
				$uris = explode("\r\n", $validator->set_value('uris'));
				foreach ($uris as $uri)
				{
					$allowed_uris[] = trim($uri);
				}
				$this->permission_model->set_permission_value($role_id, 'uri', $allowed_uris);

				$this->data['message'] = 'Update success';
			}

			$this->data['role_info'] = $this->role_model->find(array('id' => $role_id, 'status' => 1), null, 1)->row();;
			$this->data['allowed_uris'] = $this->permission_model->get_permission_value($role_id, 'uri');

			$this->template->title('SiteName', 'Nhóm người dùng', 'Chỉnh sửa');
			$this->template->build('backend/group/update', $this->data);
		}
		else
		{
			show_404();
		}
	}

	public function delete($role_id = NULL)
	{
		if($this->input->is_ajax_request())
		{
			if($role_ids = $this->input->post('items'))
			{
				foreach ((array)$role_ids as $role_id)
				{
					$this->role_model->update(array('id' => $role_id), array('status' => 0));
				}
			}

			$data['message'] = 'OK';
			die(json_encode($data));
		}
	}

	public function check_role($role)
	{
		$result = ($this->role_model->count(array('name' => $role))) ? FALSE : TRUE;
		if ( ! $result)
		{
			$this->form_validation->set_message('check_role', '%s đã tồn tại. Hãy chọn cái khác.');
		}

		return $result;
	}
}